package com.study.springbootshiro.controller;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 *
 * @author weixiaochun
 */
@Controller
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        logger.info("hello");
        return "ok";
    }


    @RequestMapping("/testThymeleaf")
    public String testThymeleaf(Model model){
        model.addAttribute("name", "张三");
        return "test";
    }

    @RequestMapping("/user/add")
    public String add(Model model){
        return "/user/add";
    }

    @RequestMapping("/user/update")
    public String update(Model model){
        return "/user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(Model model){
        return "/user/login";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("username")String username, @RequestParam("password")String password){
        logger.info("****** {} - {} ******", username, password);
        //1、过去Subject
        Subject subject = SecurityUtils.getSubject();

        //2、封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //3、执行登录方法
        try{
            subject.login(token);
            logger.info("登录成功！！！");
        }catch (UnknownAccountException e){
            logger.error("登录失败 - 用户名不存在");
            return "/user/login";
        }

        return "/test";
    }
}
